package org.xiyu.yee.onekeyminer_chainable_visual.client;

import com.mojang.blaze3d.pipeline.BlendFunction;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.platform.DepthTestFunction;
import com.mojang.blaze3d.shaders.UniformType;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormat;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.*;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.animal.sheep.Sheep;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.BooleanOp;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.neoforge.client.event.RenderLevelStageEvent;
import org.joml.Matrix4f;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.OptionalDouble;
import java.util.UUID;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.RenderStateShard;
import static net.minecraft.client.renderer.RenderStateShard.*;

import org.xiyu.yee.onekeyminer.Onekeyminer;
import org.xiyu.yee.onekeyminer.api.ChainPositionStore;
import org.xiyu.yee.onekeyminer_chainable_visual.Config;
import org.xiyu.yee.onekeyminer_chainable_visual.client.KeyBindings;

import java.util.Objects;

@OnlyIn(Dist.CLIENT)
@EventBusSubscriber(modid = "onekeyminer_chainable_visual")
public class ClientRenderHandler {

    // 默认颜色（备用，移除种植相关）
    private static final float[] COLOR_MINING = new float[]{0f, 1f, 0f, 0.45f}; // 绿色
    private static final float[] COLOR_INTERACT = new float[]{0f, 0.5f, 1f, 0.45f}; // 蓝色
    
    // 羊高亮缓存
    private static final Set<UUID> LAST_GLOWING_SHEEP = new HashSet<>();

    // 渲染类型（懒初始化）
    private static RenderType LINES_NORMAL = null;
    private static RenderType LINES_TRANSPARENT = null;
    private static RenderPipeline TRANSPARENT_LINES_PIPELINE = null;
    private static boolean PIPELINE_INIT_ATTEMPTED = false;

    private static void ensureRenderTypes() {
        // 如果调用者或配置禁用了自定义 RenderType，则只使用默认 lines()
        try {
            boolean useCustom = false;
            try {
                useCustom = Config.useCustomRenderTypes();
            } catch (Throwable ignored) {
                // 配置读取失败时默认禁用自定义类型（保持兼容）
                useCustom = false;
            }

            if (!useCustom) {
                // 直接使用 vanilla lines，避免可能的兼容性问题
                LINES_NORMAL = RenderType.lines();
                LINES_TRANSPARENT = RenderType.lines();
                return;
            }

            if (LINES_NORMAL != null && LINES_TRANSPARENT != null) return;

            // 尝试创建 Liteminer 风格的透明线条 RenderPipeline
            LINES_NORMAL = RenderType.lines();
            
            if (!PIPELINE_INIT_ATTEMPTED) {
                PIPELINE_INIT_ATTEMPTED = true;
                try {
                    // 使用反射调用私有的 RenderPipelines.register 方法
                    Method registerMethod = RenderPipelines.class.getDeclaredMethod("register", RenderPipeline.class);
                    registerMethod.setAccessible(true);
                    TRANSPARENT_LINES_PIPELINE = (RenderPipeline) registerMethod.invoke(null, RenderPipeline.builder(RenderPipelines.MATRICES_COLOR_FOG_SNIPPET)
                            .withVertexShader("core/rendertype_lines")
                            .withFragmentShader("core/rendertype_lines")
                            .withUniform("LineWidth", UniformType.FLOAT)
                            .withUniform("ScreenSize", UniformType.VEC2)
                            .withBlend(BlendFunction.TRANSLUCENT)
                            .withCull(false)
                            .withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST)
                            .withVertexFormat(DefaultVertexFormat.POSITION_COLOR, VertexFormat.Mode.DEBUG_LINES)
                            .withLocation("pipeline/transparent_lines")
                            .build());

                    LINES_TRANSPARENT = RenderType.create(
                            "lines_transparent",
                            1536, TRANSPARENT_LINES_PIPELINE,
                            RenderType.CompositeState.builder()
                                    .setLineState(new LineStateShard(OptionalDouble.empty()))
                                    .setLayeringState(NO_LAYERING)
                                    .setOutputState(ITEM_ENTITY_TARGET)
                                    .createCompositeState(false)
                    );
                } catch (Throwable pipelineError) {
                    // Pipeline 注册失败，回退到普通 lines()
                    try {
                        Onekeyminer.LOGGER.warn("Failed to register TRANSPARENT_LINES_PIPELINE, falling back to RenderType.lines(): {}", pipelineError.toString());
                    } catch (Throwable ignored) {}
                    TRANSPARENT_LINES_PIPELINE = null;
                    LINES_TRANSPARENT = RenderType.lines();
                }
            } else {
                // Pipeline 初始化已尝试过
                LINES_TRANSPARENT = (TRANSPARENT_LINES_PIPELINE != null) ? 
                    RenderType.create(
                            "lines_transparent",
                            1536, TRANSPARENT_LINES_PIPELINE,
                            RenderType.CompositeState.builder()
                                    .setLineState(new LineStateShard(OptionalDouble.empty()))
                                    .setLayeringState(NO_LAYERING)
                                    .setOutputState(ITEM_ENTITY_TARGET)
                                    .createCompositeState(false)
                    ) : RenderType.lines();
            }
        } catch (Throwable t) {
            // 在任何异常情况下记录一次警告，然后回退到最保守的实现
            try {
                Onekeyminer.LOGGER.warn("ensureRenderTypes failed, falling back to RenderType.lines(): {}", t.toString());
            } catch (Throwable ignored) {}
            LINES_NORMAL = RenderType.lines();
            LINES_TRANSPARENT = RenderType.lines();
        }
    }



    @SubscribeEvent
    public static void onRenderLevelStage(RenderLevelStageEvent event) {
        if (event.getStage() != RenderLevelStageEvent.Stage.AFTER_TRANSLUCENT_BLOCKS) return;

        PoseStack poseStack = event.getPoseStack();
        Minecraft mc = Minecraft.getInstance();
        if (mc == null || mc.gameRenderer == null || mc.player == null) return;

        MultiBufferSource.BufferSource bufferSource = mc.renderBuffers().bufferSource();
        Vec3 camPos = mc.gameRenderer.getMainCamera().getPosition();
        String playerUuid = mc.player.getUUID().toString();

        // 直接获取实时位置 - 无需任何缓存机制
        List<BlockPos> mining = ChainPositionStore.getMiningPositions(playerUuid);
        List<BlockPos> interact = ChainPositionStore.getInteractionPositions(playerUuid);

        // 读取配置和按键状态
        boolean configShowMining = Config.isShowMining();
        boolean configShowInteract = Config.isShowInteraction();
        boolean isInteractionKeyPressed = KeyBindings.isShowInteractionKeyPressed();
        boolean configShowThroughWalls = Config.isShowThroughWalls();
        boolean configOutlineMode = Config.isOutlineMode();
        
        // 根据按键状态决定显示模式：
        // 按住Shift时显示交互高亮，否则显示挖掘高亮
        boolean showMining = configShowMining && !isInteractionKeyPressed;
        boolean showInteract = configShowInteract && isInteractionKeyPressed;

        float[] miningColor = Config.getMiningColor();
        float[] interactColor = Config.getInteractionColor();

        // 平移矩阵（抵消相机位置，确保方块在世界中正确渲染）
        poseStack.pushPose();
        poseStack.translate(-camPos.x, -camPos.y, -camPos.z);

        // 十字准星追踪（原逻辑保留）
        tryRequestRecomputeIfNeeded(mc);

        // 渲染各类型方块（移除种植渲染）
        try {
            ensureRenderTypes();
            if (showMining) renderBoxes(poseStack, bufferSource, mining, miningColor, configOutlineMode, configShowThroughWalls);
            if (showInteract) renderBoxes(poseStack, bufferSource, interact, interactColor, configOutlineMode, configShowThroughWalls);
            
            // 渲染羊高亮（替代mixin中的setGlowingTag）
            renderSheepHighlight(poseStack, bufferSource, mc, playerUuid, camPos, configShowThroughWalls);
        } catch (Exception e) {
            // 渲染失败，记录错误但不崩溃游戏
            try {
                Onekeyminer.LOGGER.warn("Failed to render visual highlights: {}", e.toString());
            } catch (Throwable ignored) {}
        }

        poseStack.popPose();
        // 确保所有缓冲区刷新（如果某些类型在 renderBoxes 内没有 endBatch，会在这里强制结束）
        try {
            bufferSource.endBatch();
        } catch (Throwable ignored) {}
    }


    private static void renderBoxes(PoseStack poseStack,
                                    MultiBufferSource.BufferSource bufferSource,
                                    java.util.List<BlockPos> positions,
                                    float[] color,
                                    boolean outlineMode,
                                    boolean showThroughWalls) {
        if (positions == null || positions.isEmpty()) return;

        // 合并所有方块的碰撞箱（减少渲染次数）
        VoxelShape mergedShape = Shapes.empty();
        for (BlockPos pos : positions) {
            AABB blockAabb = new AABB(pos).inflate(0.002d); // 轻微膨胀避免与原方块重叠
            mergedShape = Shapes.joinUnoptimized(mergedShape, Shapes.create(blockAabb), BooleanOp.OR);
        }
        if (mergedShape.isEmpty()) return;

        PoseStack.Pose pose = poseStack.last();
        Matrix4f modelMatrix = pose.pose();

        // 1. 渲染线框（使用确保过的 render types）
        RenderType normalType = LINES_NORMAL == null ? RenderType.lines() : LINES_NORMAL;
        RenderType transparentType = LINES_TRANSPARENT == null ? RenderType.lines() : LINES_TRANSPARENT;

        // 根据配置选择渲染类型
        RenderType selectedType = showThroughWalls ? transparentType : normalType;

        // 使用选择的渲染类型
        try {
            VertexConsumer lineConsumer = bufferSource.getBuffer(selectedType);
            mergedShape.forAllEdges((x1, y1, z1, x2, y2, z2) -> {
                try {
                    // 根据穿墙配置决定是否计算法向量
                    if (showThroughWalls) {
                        // 计算边的法向量（Liteminer 风格）
                        final double dx = x2 - x1;
                        final double dy = y2 - y1;
                        final double dz = z2 - z1;
                        final double mag = Math.sqrt(dx * dx + dy * dy + dz * dz);
                        if (mag > 0.0001) { // 避免除零错误
                            final double invMag = 1.0 / mag;
                            final float nx = (float) (dx * invMag);
                            final float ny = (float) (dy * invMag);
                            final float nz = (float) (dz * invMag);
                            
                            addLineVertexWithNormal(lineConsumer, modelMatrix, pose, x1, y1, z1, color, nx, ny, nz);
                            addLineVertexWithNormal(lineConsumer, modelMatrix, pose, x2, y2, z2, color, nx, ny, nz);
                        }
                    } else {
                        // 普通线条渲染
                        addLineVertex(lineConsumer, modelMatrix, pose, x1, y1, z1, color);
                        addLineVertex(lineConsumer, modelMatrix, pose, x2, y2, z2, color);
                    }
                } catch (Exception e) {
                    // 忽略单个边的渲染错误，继续处理其他边
                }
            });
            // 结束 selectedType 批次
            bufferSource.endBatch(selectedType);
        } catch (Exception e) {
            // 线条渲染失败，记录错误但继续
            try {
                Onekeyminer.LOGGER.warn("Failed to render lines: {}", e.toString());
            } catch (Throwable ignored) {}
        }

        // 可选：渲染对比线条（仅在非透明模式下添加透明效果）
        if (!showThroughWalls && outlineMode) {
            try {
                VertexConsumer contrastConsumer = bufferSource.getBuffer(transparentType);
                float[] contrastColor = new float[]{color[0], color[1], color[2], color[3] * 0.3f}; // 更透明的对比色
                mergedShape.forAllEdges((x1, y1, z1, x2, y2, z2) -> {
                    try {
                        addLineVertex(contrastConsumer, modelMatrix, pose, x1, y1, z1, contrastColor);
                        addLineVertex(contrastConsumer, modelMatrix, pose, x2, y2, z2, contrastColor);
                    } catch (Exception e) {
                        // 忽略单个边的渲染错误
                    }
                });
                bufferSource.endBatch(transparentType);
            } catch (Exception e) {
                try {
                    Onekeyminer.LOGGER.warn("Failed to render contrast lines: {}", e.toString());
                } catch (Throwable ignored) {}
            }
        }

        // 可选：渲染外层轮廓（仅在轮廓模式启用时）
        if (outlineMode) {
            try {
                VertexConsumer outlineConsumer = bufferSource.getBuffer(normalType);
                float outlineAlpha = color[3] * 0.6f;
                float[] outlineColor = new float[]{color[0], color[1], color[2], outlineAlpha};

                // 外层轮廓偏移（正负各偏移0.01）
                for (double offset : new double[]{-0.01, 0.01}) {
                    try {
                        VoxelShape outlineShape = Shapes.empty();
                        for (AABB aabb : mergedShape.toAabbs()) {
                            AABB outlineAabb = aabb.inflate(offset);
                            outlineShape = Shapes.joinUnoptimized(outlineShape, Shapes.create(outlineAabb), BooleanOp.OR);
                        }
                        outlineShape.forAllEdges((x1, y1, z1, x2, y2, z2) -> {
                            try {
                                addLineVertex(outlineConsumer, modelMatrix, pose, x1, y1, z1, outlineColor);
                                addLineVertex(outlineConsumer, modelMatrix, pose, x2, y2, z2, outlineColor);
                            } catch (Exception e) {
                                // 忽略单个边的渲染错误
                            }
                        });
                        bufferSource.endBatch(normalType);
                    } catch (Exception e) {
                        // 忽略单个轮廓层的错误，继续处理其他层
                    }
                }
            } catch (Exception e) {
                // 外层轮廓渲染失败，记录错误但继续
                try {
                    Onekeyminer.LOGGER.warn("Failed to render outline: {}", e.toString());
                } catch (Throwable ignored) {}
            }
        }

        // 我们现在仅使用线框/轮廓来代表方块位置（面填充被移除以保证兼容性和稳定性）
    }


    // 辅助：添加线框顶点（使用更通用的 VertexConsumer API）
    private static void addLineVertex(VertexConsumer vc, Matrix4f matrix, PoseStack.Pose pose,
                                      double x, double y, double z, float[] color) {
        try {
            // 使用正确的顶点数据添加方式，添加安全检查
            if (vc != null && pose != null && color != null && color.length >= 4) {
                vc.addVertex(pose, (float) x, (float) y, (float) z)
                        .setColor(color[0], color[1], color[2], color[3])
                        .setNormal(pose, 0f, 1f, 0f);
            }
        } catch (Exception e) {
            // 静默处理顶点添加错误，避免崩溃
        }
    }

    // 辅助：添加线框顶点（带法向量，Liteminer 风格）
    private static void addLineVertexWithNormal(VertexConsumer vc, Matrix4f matrix, PoseStack.Pose pose,
                                               double x, double y, double z, float[] color,
                                               float nx, float ny, float nz) {
        try {
            // 使用正确的顶点数据添加方式，添加安全检查
            if (vc != null && pose != null && color != null && color.length >= 4) {
                vc.addVertex(pose, (float) x, (float) y, (float) z)
                        .setColor(color[0], color[1], color[2], color[3])
                        .setNormal(pose, nx, ny, nz);
            }
        } catch (Exception e) {
            // 静默处理顶点添加错误，避免崩溃
        }
    }


    // 辅助：添加四边形顶点（如需要时可被启用）
    private static void addQuad(VertexConsumer vc, Matrix4f matrix, PoseStack.Pose pose,
                                float x1, float y1, float z1, float x2, float y2, float z2,
                                float nx, float ny, float nz, float[] color, float alpha) {
        vc.addVertex(matrix, x1, y1, z1)
                .setColor(color[0], color[1], color[2], alpha)
                .setNormal(pose, nx, ny, nz);

        vc.addVertex(matrix, x2, y1, z1)
                .setColor(color[0], color[1], color[2], alpha)
                .setNormal(pose, nx, ny, nz);

        vc.addVertex(matrix, x2, y2, z2)
                .setColor(color[0], color[1], color[2], alpha)
                .setNormal(pose, nx, ny, nz);

        vc.addVertex(matrix, x1, y2, z2)
                .setColor(color[0], color[1], color[2], alpha)
                .setNormal(pose, nx, ny, nz);
    }


    // 辅助：将配置的double颜色转为float数组（原逻辑保留）
    private static float[] toFloatColor(double[] src, float[] fallback) {
        if (src == null || src.length < 4) return fallback;
        float[] out = new float[4];
        try {
            out[0] = (float) src[0];
            out[1] = (float) src[1];
            out[2] = (float) src[2];
            out[3] = (float) src[3];
        } catch (Exception e) {
            return fallback;
        }
        return out;
    }


    // 十字准星追踪（原逻辑保留，但禁用网络请求防止与主模组冲突）
    private static BlockPos lastTargetPos = null;
    private static final long REQUEST_THROTTLE_MS = 250L;
    private static long lastRequestTime = 0L;

    private static void tryRequestRecomputeIfNeeded(Minecraft mc) {
        if (mc == null || mc.player == null) return;
        String uuid = mc.player.getUUID().toString();

        // 仅当连锁模式激活时请求重新计算
        if (!ChainPositionStore.isChainModeActive(uuid)) {
            lastTargetPos = null;
            return;
        }

        // 获取当前准星指向的方块
        net.minecraft.world.phys.HitResult hitResult = mc.hitResult;
        BlockPos currentTarget = null;
        if (hitResult != null && hitResult.getType() == net.minecraft.world.phys.HitResult.Type.BLOCK) {
            currentTarget = ((net.minecraft.world.phys.BlockHitResult) hitResult).getBlockPos();
        }

        // 目标变化且节流时间到，发送请求
        long now = System.currentTimeMillis();
        if (!Objects.equals(currentTarget, lastTargetPos) && now - lastRequestTime >= REQUEST_THROTTLE_MS) {
            lastRequestTime = now;
            lastTargetPos = currentTarget;
            // 禁用网络请求 - 避免与主模组的网络处理冲突
            // 主模组会自动处理连锁计算，无需附属模组干预
            /*
            try {
                // 复用现有数据包请求服务器重新计算
                org.xiyu.yee.onekeyminer.network.ChainModePacket packet = new org.xiyu.yee.onekeyminer.network.ChainModePacket(true);
                org.xiyu.yee.onekeyminer.network.NetworkHandler.sendToServer(packet);
            } catch (Exception e) {
                // 静默处理（尽力而为，不阻断渲染）
            }
            */
        }
    }

    /**
     * 渲染羊高亮（替代 mixin 中的 setGlowingTag）
     */
    private static void renderSheepHighlight(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource,
                                           Minecraft mc, String playerUuid, Vec3 camPos, boolean showThroughWalls) {
        try {
            // 检查配置是否启用剪羊毛高亮
            if (!Config.isShearingEnabled()) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }

            // 检查玩家是否手持剪刀
            ItemStack mainHand = mc.player.getMainHandItem();
            ItemStack offHand = mc.player.getOffhandItem();
            if (!mainHand.is(Items.SHEARS) && !offHand.is(Items.SHEARS)) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }

            // 检查连锁模式是否开启
            boolean chainModeEnabled = false;
            try {
                chainModeEnabled = ChainPositionStore.isChainModeActive(playerUuid);
            } catch (Throwable t) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }
            if (!chainModeEnabled) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }

            // 检查玩家是否正在瞄准羊
            HitResult hitResult = mc.hitResult;
            if (!(hitResult instanceof EntityHitResult ehr) || !(ehr.getEntity() instanceof Sheep)) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }

            // 获取 API 返回的羊 UUID 列表
            List<UUID> shearingUuids;
            try {
                shearingUuids = ChainPositionStore.getShearingEntityUuids(playerUuid);
            } catch (Throwable t) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }
            if (shearingUuids == null || shearingUuids.isEmpty()) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }

            // 获取范围内的所有羊
            double range = Config.getShearingRange();
            List<Sheep> allSheep = mc.level.getEntitiesOfClass(Sheep.class, mc.player.getBoundingBox().inflate(range));
            if (allSheep.isEmpty()) {
                LAST_GLOWING_SHEEP.clear();
                return;
            }

            // 收集需要高亮的羊
            Set<UUID> currentGlowingSheep = new HashSet<>();
            List<AABB> sheepBoxes = new java.util.ArrayList<>();
            
            for (Sheep sheep : allSheep) {
                if (shearingUuids.contains(sheep.getUUID()) && sheep.isAlive() && sheep.readyForShearing()) {
                    currentGlowingSheep.add(sheep.getUUID());
                    // 获取羊的边界框，稍微扩大以避免与羊模型重叠
                    AABB sheepBox = sheep.getBoundingBox().inflate(0.1);
                    sheepBoxes.add(sheepBox);
                }
            }

            // 更新缓存
            LAST_GLOWING_SHEEP.clear();
            LAST_GLOWING_SHEEP.addAll(currentGlowingSheep);

            // 如果没有需要高亮的羊，直接返回
            if (sheepBoxes.isEmpty()) return;

            // 渲染羊的轮廓
            float[] shearingColor = Config.getShearingColor();
            renderSheepOutlines(poseStack, bufferSource, sheepBoxes, shearingColor, showThroughWalls);

        } catch (Exception e) {
            try {
                Onekeyminer.LOGGER.warn("Failed to render sheep highlight: {}", e.toString());
            } catch (Throwable ignored) {}
        }
    }

    /**
     * 渲染羊轮廓
     */
    private static void renderSheepOutlines(PoseStack poseStack, MultiBufferSource.BufferSource bufferSource,
                                          List<AABB> sheepBoxes, float[] color, boolean showThroughWalls) {
        try {
            // 确保渲染类型已初始化
            ensureRenderTypes();
            
            PoseStack.Pose pose = poseStack.last();
            Matrix4f modelMatrix = pose.pose();

            // 选择渲染类型
            RenderType normalType = LINES_NORMAL == null ? RenderType.lines() : LINES_NORMAL;
            RenderType transparentType = LINES_TRANSPARENT == null ? RenderType.lines() : LINES_TRANSPARENT;
            RenderType selectedType = showThroughWalls ? transparentType : normalType;

            VertexConsumer lineConsumer = bufferSource.getBuffer(selectedType);

            // 为每只羊渲染边界框轮廓
            for (AABB box : sheepBoxes) {
                // 渲染边界框的12条边
                renderAABBOutline(lineConsumer, pose, box, color);
            }

            // 结束批次
            bufferSource.endBatch(selectedType);

        } catch (Exception e) {
            try {
                Onekeyminer.LOGGER.warn("Failed to render sheep outlines: {}", e.toString());
            } catch (Throwable ignored) {}
        }
    }

    /**
     * 渲染 AABB 的轮廓线
     */
    private static void renderAABBOutline(VertexConsumer consumer, PoseStack.Pose pose, AABB box, float[] color) {
        // 获取边界框的8个顶点
        float minX = (float) box.minX;
        float minY = (float) box.minY;
        float minZ = (float) box.minZ;
        float maxX = (float) box.maxX;
        float maxY = (float) box.maxY;
        float maxZ = (float) box.maxZ;

        // 底面的4条边
        addLine(consumer, pose, minX, minY, minZ, maxX, minY, minZ, color); // 前边
        addLine(consumer, pose, maxX, minY, minZ, maxX, minY, maxZ, color); // 右边
        addLine(consumer, pose, maxX, minY, maxZ, minX, minY, maxZ, color); // 后边
        addLine(consumer, pose, minX, minY, maxZ, minX, minY, minZ, color); // 左边

        // 顶面的4条边
        addLine(consumer, pose, minX, maxY, minZ, maxX, maxY, minZ, color); // 前边
        addLine(consumer, pose, maxX, maxY, minZ, maxX, maxY, maxZ, color); // 右边
        addLine(consumer, pose, maxX, maxY, maxZ, minX, maxY, maxZ, color); // 后边
        addLine(consumer, pose, minX, maxY, maxZ, minX, maxY, minZ, color); // 左边

        // 垂直的4条边
        addLine(consumer, pose, minX, minY, minZ, minX, maxY, minZ, color); // 前左
        addLine(consumer, pose, maxX, minY, minZ, maxX, maxY, minZ, color); // 前右
        addLine(consumer, pose, maxX, minY, maxZ, maxX, maxY, maxZ, color); // 后右
        addLine(consumer, pose, minX, minY, maxZ, minX, maxY, maxZ, color); // 后左
    }

    /**
     * 添加一条线段
     */
    private static void addLine(VertexConsumer consumer, PoseStack.Pose pose, 
                               float x1, float y1, float z1, float x2, float y2, float z2, float[] color) {
        try {
            consumer.addVertex(pose, x1, y1, z1)
                   .setColor(color[0], color[1], color[2], color[3])
                   .setNormal(pose, 0f, 1f, 0f);
                   
            consumer.addVertex(pose, x2, y2, z2)
                   .setColor(color[0], color[1], color[2], color[3])
                   .setNormal(pose, 0f, 1f, 0f);
        } catch (Exception e) {
            // 静默处理单条线的渲染错误
        }
    }
}
